package com.haierCamera.customapplication.ui.main;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkRequest;
import android.net.NetworkSpecifier;
//import android.net.wifi.WifiNetworkSpecifier;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.PatternMatcher;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.haierCamera.customapplication.BaseActivity;
import com.haierCamera.customapplication.Constants;
import com.haierCamera.customapplication.R;
import com.haierCamera.customapplication.api.ApiService;
import com.haierCamera.customapplication.api.vo.GetDeviceEntity;
import com.haierCamera.customapplication.databinding.HzklActivityMonitorBinding;
import com.haierCamera.customapplication.ui.business.Business;
import com.haierCamera.customapplication.ui.business.util.WifiManagerUtil;
import com.haierCamera.customapplication.ui.custom.BaseListenerOnClik;
import com.haierCamera.customapplication.ui.custom.GridLayoutColorDivider;
import com.haierCamera.customapplication.ui.custom.LinearLayoutColorDivider;
import com.haierCamera.customapplication.ui.mediaplay.MediaPlayActivity;
import com.haierCamera.customapplication.ui.zxing.activity.CaptureActivity;
import com.haierCamera.customapplication.utils.DensityUtil;
import com.haierCamera.customapplication.utils.NoDoubleClickListener;
import com.haierCamera.customapplication.utils.ResourceConvertUtils;
import com.haierCamera.customapplication.utils.SharedPreferencesUtils;
import com.haierCamera.customapplication.utils.android.HttpErrorProcess;

import java.util.List;

import javax.inject.Inject;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import dagger.Lazy;

public class HZKLMyCameraDeviceActivity extends BaseActivity {

    HzklActivityMonitorBinding binding;

    @Inject
    Lazy<HttpErrorProcess> httpErrorProcessLazy;
    @Inject
    ApiService apiService;

    CameraDeviceListAdapter adapter;
    List<GetDeviceEntity> list;

    WifiManagerUtil managerUtil;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.hzkl_activity_monitor);
        binding.imgReturn.setOnClickListener((v)->{
            finish();
        });

        processWithPermission(()->{
//            connectWifi();
//            WifiUtils.getInstance(this).connectWifiPws(ssid,password);
        }, Manifest.permission.ACCESS_COARSE_LOCATION);
        processWithPermission(()->{
        }, Manifest.permission.ACCESS_FINE_LOCATION);
        processWithPermission(()->{
        }, Manifest.permission.ACCESS_WIFI_STATE);
        processWithPermission(()->{
        }, Manifest.permission.CHANGE_WIFI_STATE);

        binding.ivAddCamera.setOnClickListener(new NoDoubleClickListener() {
            @Override
            protected void onNoDoubleClick(View v) {
                processWithPermission(()->{
                    Log.i("TAG","runnable---");
                    startActivityForResult(new Intent(HZKLMyCameraDeviceActivity.this
                            , CaptureActivity.class)
                            .putExtra("type","1"),100);
//                    startActivity(new Intent(HZKLMyCameraDeviceActivity.this
//                            , HZKLSoftAPAddActivity.class)
//                            .putExtra("sn", "6A0376DPAJ13266")
//                            .putExtra("sc", "L2B6E508")
//                            .putExtra("dt", "TP7S"));
                }, Manifest.permission.CAMERA);

            }
        });

        binding.ivEditView.setOnClickListener((v)->{

            if (adapter.getType() == 0) {
                binding.rcv.setLayoutManager(new GridLayoutManager(this, 2));
                binding.rcv.removeItemDecorationAt(0);
                binding.rcv.addItemDecoration(new GridLayoutColorDivider(this
                        , 0x00000000
                        , DensityUtil.dip2px(this, 5)
                        , DensityUtil.dip2px(this, 5)));
                adapter.setType(1);
                binding.ivEditView.setImageResource(R.drawable.hzkl_home_edit_view_lin);

            } else if (adapter.getType() == 1) {
                binding.rcv.setLayoutManager(new LinearLayoutManager(this));
                binding.rcv.removeItemDecorationAt(0);
                binding.rcv.addItemDecoration(new LinearLayoutColorDivider(this
                        , 0x00000000
                        , DensityUtil.dip2px(this, 5)
                        , DensityUtil.dip2px(this, 5)));
                adapter.setType(0);
                binding.ivEditView.setImageResource(R.drawable.hzkl_home_edit_view);

            }
        });

        binding.swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                list.clear();
                adapter.upDate(list);
                getDevice();
            }
        });

        adapter= new CameraDeviceListAdapter(this);
        binding.rcv.setLayoutManager(new LinearLayoutManager(this));
//        binding.rcv.setLayoutManager(new GridLayoutManager(getActivity(),2));
        binding.rcv.setAdapter(adapter);
        binding.rcv.addItemDecoration(new LinearLayoutColorDivider(this
                ,0x00000000
                , DensityUtil.dip2px(this,5)
                ,DensityUtil.dip2px(this,5)));
        adapter.setType(0);
        adapter.setActivity(this);

        managerUtil = new WifiManagerUtil(this);

    }

    public void getDevice() {
        ResourceConvertUtils.convertToResource(apiService.getDevice())
                .observe(this, resource -> {
                    assert resource != null;
                    switch (resource.status) {
                        case ERROR:
                            httpErrorProcessLazy.get().process(resource);
//                            binding.swipe.setRefreshing(false);
                            break;
                        case SUCCESS:
                            Log.i("TAG","getDevice-success");
                            list = resource.data;
                            binding.swipe.setRefreshing(false);
                            adapter.upDate(resource.data);
                            Business.getInstance().setmDeviceList(resource.data);
                            adapter.setOnItemOnClick(new BaseListenerOnClik() {
                                @Override
                                public void onClick(int position) {
                                    getDeviceChannel(list.get(position).serialNumber,position);
                                }
                            });
                            if (list.size() >0) {
                                binding.rcv.setVisibility(View.VISIBLE);
                                binding.ivEmpty.setVisibility(View.GONE);
                            } else {
                                binding.rcv.setVisibility(View.GONE);
                                binding.ivEmpty.setVisibility(View.VISIBLE);
                            }
                            break;
                        case LOADING:
                            break;

                    }
                });
    }

    private void getDeviceChannel(String sn ,int i){
        showLoadingDialog();
        Business.getInstance().getDeviceInfo2(sn,new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                if (msg.what == 0) {
                    Log.i("TAG","size-" + ((Bundle) msg.obj).getIntegerArrayList("list").size());

                    for (int j = 0; j < ((Bundle) msg.obj).getIntegerArrayList("list").size(); j++) {
                        Log.i("TAG","getDeviceChannel-" + ((Bundle) msg.obj).getIntegerArrayList("list").get(j));
                    }
                    dismissLoadingDialog();
                    startActivity(new Intent(HZKLMyCameraDeviceActivity.this, MediaPlayActivity.class)
                            .putExtra("TYPE", 1)
                            .putExtra("RESID", "0")
                            .putExtra("RESDEVICEID", list.get(i).serialNumber)
                            .putExtra("RESPWD", list.get(i).securityCode)
                            .putExtra("RESNAME", list.get(i).name)
                            .putExtra("RESACCOUNTDEVICEID", list.get(i).accountDeviceId)
                            .putExtra("RESPICTURE", list.get(i).picture)
                            .putExtra("RESCHANNELS", ((Bundle) msg.obj).getIntegerArrayList("list")));
                }

            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();

        String token = SharedPreferencesUtils.getString(Constants.SP_USER_TOKEN, "");
        if (!TextUtils.isEmpty(token)) {
            getDevice();
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i("TAG","HomeFragment-onActivityResult-result-" + resultCode + "/" + "requestCode-" + requestCode);
        if (resultCode == -1){
            switch (requestCode) {
                case 100:
                    Log.i("TAG","getData-" + data.getExtras().getString("result"));
                    String sn = data.getExtras().getString("sn");
                    String sc = data.getExtras().getString("sc");
                    String dt = data.getExtras().getString("dt");
//                    JSONObject json = parseJson(s);
//
//                    if (json != null) {
//                        String sn = "";
//                        try {
//                            sn = json.getString("SN");
//                        } catch (JSONException e) {
//                            e.printStackTrace();
//                        }
//
//
//
//                        String sc = "";
//                        if (s != null && s.contains("SC:")) {
//
//                            try {
//                                sc = json.getString("SC");
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        } else if (s != null && s.contains("RC:")) {
//                            try {
//                                sc = json.getString("RC");
//                            } catch (JSONException e) {
//                                e.printStackTrace();
//                            }
//                        }
                    Log.i("TAG","sn-" +sn + "/sc-" + sc);
                    startActivity(new Intent(this, CameraDeviceAddActivity.class)
                            .putExtra("sn", sn)
                            .putExtra("sc", sc)
                            .putExtra("dt", dt));

//                    }
                    break;
                default:
                    break;
            }
        }
    }

}
